'''



'''

import json
import os


class WebConfig(Exception):
    def __init__(self, msg):
        super().__init__(msg)


class Config:
    '''
    配置信息

    '''

    def __init__(self, name='', **kwargs):
        self.name = name
        self.type = kwargs.get("type", None)
        self.information = kwargs.get("information", None)

        # self._instance = None

    # 将类的实例转成字典
    def to_dict(self):
        # resource_dict=dict()
        # for key,value in self.__dict__.items():
        #     resource_dict[key]=value

        resource_dict = {key: value for key, value in self.__dict__.items()}
        return resource_dict

    # 根据字典数据，创建配置资源对象
    @staticmethod
    def from_dict(dict_obj: dict):
        web_resource = Config()
        for key, value in dict_obj.items():
            setattr(web_resource, key, value)

        return web_resource

    def __repr__(self):
        return self.name


class WebEnvironment:
    '''
    测试环境类：用于管理资源和配置



    '''

    def __init__(self):
        self.information = dict()
        self.resoure_bed = dict()

    # 添加配置资源
    def add_resoure(self, resoure_name, **kwargs):
        if resoure_name in self.resoure_bed:
            raise WebConfig(f'测试资源{resoure_name}已存在，不能重复添加')
        self.resoure_bed[resoure_name] = Config(resoure_name)

    # 重新初始化测试环境（清空测试资源）
    # def reboot(self):
    #     self.resoure_bed.clear()
    #     self.information.clear()
    #
    #     self.is_used = None

    def load_file(self, filename):
        # 判断文件是否存在
        if not os.path.exists(filename):
            raise WebConfig(f'没有找到{filename}')

        # self.reboot()

        with open(filename) as file:
            json_obj = json.load(file)
            if 'info' in json_obj:
                self.information = json_obj['info']
            for key, value in json_obj['config'].items():
                web_resource = Config.from_dict(value)
                # print(key,value)
                # print(web_resource.information)
                self.resoure_bed[key] = web_resource
        return self.resoure_bed

    def save_file(self, filename):
        with open(filename, mode='w') as file:
            root_object = dict()
            root_object['config'] = dict()

            root_object['info'] = [self.information, ]
            for key, resource in self.resoure_bed.items():
                res_dict = resource.to_dict()
                root_object['config'][key] = res_dict
                root_object['info'].append(res_dict['name'])
            json.dump(root_object, file, indent=4, ensure_ascii=False)

    # 用于筛选满足条件的测试配置资源 ,默认筛选条件为资源的类型属性,若传入name属性则从筛选过后的类型资源中再次过滤出名称相同的资源
    def filter_resoure(self, resoure_type, *, name=None):

        filter_list = list()
        for key, value in self.resoure_bed.items():
            if value.type == resoure_type:
                if not name:
                    filter_list.append(value)
                else:
                    if value.name in name:
                        filter_list.append(value)

        return filter_list


if __name__ == '__main__':
    # config_=[{'url':'https://www.baidu.com/'},{'测试类型':'回归测试'},{'元素显性等待时间':'30'}]
    # pc1=Config("百度系统",type='UI自动化',information=config_)
    # # pc3 = Config("百度系统", type='接口测试', information='接口测试')
    # # pc2=Config("服务器",type='自动化测试机器',information="主线测试环境")
    # # webapi=Config("日志记录等级",type='debug',information="调试")
    # # # print(pc1.to_dict())
    testbed = WebEnvironment()
    # testbed.resoure_bed['pc1']=pc1
    # # testbed.resoure_bed['pc2']=pc2
    # # testbed.resoure_bed['webapi']=webapi
    # # print(testbed.resoure_bed)
    # testbed.save_file('环境配置.json')
    resources_dict = testbed.load_file('环境配置.json')

    con_list = resources_dict['pc1'].information

    print(con_list[2]['元素显性等待时间'])
    # CONFIG = resources_dict['pc1'].information
    # WAIT = int(CONFIG[2].value)
    # url = CONFIG[0].value

    # filter_=testbed.filter_resoure('百度系统',name="UI自动化")
